import os
import cgi

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

from core import model

PAGE_SIZE = 6

class MainPage(webapp.RequestHandler):
    def get(self):
        
        try:
            page = self.request.path[self.request.path.rindex('/')+1:]
            page = int(page)
        except:
            page = 1

        query = model.CodeSnippet.gql('ORDER BY created_at DESC')
        snippets = query.fetch(PAGE_SIZE, PAGE_SIZE * (page-1))
        prev_page = page - 1
        next_page = page + 1
        if len(snippets) < 6:
            next_page = 0

        data = {
                'snippets' : snippets,
                'prev_page' : prev_page,
                'next_page' : next_page,
                }
        path = os.path.join(os.path.dirname(__file__), 'themes/default/index.html')
        self.response.out.write(template.render(path, data))
        
class NewPage(webapp.RequestHandler):
    def get(self):
        data = {}
        path = os.path.join(os.path.dirname(__file__), 'themes/default/new.html')
        self.response.out.write(template.render(path, data))
    
    def post(self):
        snippet = model.CodeSnippet()
        snippet.title = cgi.escape(self.request.get('title')).strip()
        snippet.language = cgi.escape(self.request.get('language')).strip()
        snippet.code = cgi.escape(self.request.get('code')).strip()
        snippet.comment = cgi.escape(self.request.get('comment')).strip()
        if snippet.title == '' or snippet.code == '':
            self.response.out.write('invalid.')
        else: 
            snippet.save()
            self.redirect('/')
        
class DebugPage(webapp.RequestHandler):
    def get(self):
        
        pass
        
application = webapp.WSGIApplication(
                                    [ 
                                     ('/', MainPage),
                                     ('/\d+', MainPage),
                                     ('/new', NewPage), 
                                     ('/debug.*', DebugPage),
                                    ],
                                    debug=True
                                    )

def main():
    run_wsgi_app(application)
    
if __name__ == '__main__':
    main()
    
